// src/api/request.ts
import axios from 'axios'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'

export let USE_MOCK = false
export function setMockMode(useMock: boolean) {
  USE_MOCK = useMock
  console.log(`[request] 全局开关已设置为: ${USE_MOCK ? 'Mock模式' : '真实后端模式'}`)
}

/* ---------- 1. axios 实例 ---------- */
export const service = axios.create({
  baseURL: 'http://ljxg.free.idcfengye.com', // 去掉末尾空格
  timeout: 10000
})

/* ---------- 2. 请求拦截：自动带 token ---------- */
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      // 后端支持 Bearer 就保留；否则改成 config.headers.token = token
    // config.headers.Authorization = `Bearer ${token}`
   // ① 保证 headers 存在
   config.headers = config.headers || {}
   // ② 再写 Authorization
   config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

/* ---------- 3. 响应拦截：统一报错 ---------- */
service.interceptors.response.use(
  (res: AxiosResponse) => res.data,
  error => {
    // 统一错误提示（可选）
    return Promise.reject(error)
  }
)

/* ---------- 4. 通用 request ---------- */
export async function request<T>(config: AxiosRequestConfig, mockData?: T): Promise<T> {

    await new Promise(resolve => setTimeout(resolve, 300))

  const res: AxiosResponse<T> = await service.request<T>(config)
  return res.data
}
